package com.xiyuan.service.impl;

import com.xiyuan.constant.MessageConstant;
import com.xiyuan.mapper.UserMapper;
import com.xiyuan.pojo.entity.User;
import com.xiyuan.service.UserService;
import com.xiyuan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    /**
     * 根据账号查询用户信息
     * @param username
     * @return
     */
    @Override
    public User findByUserName(String username) {
        return userMapper.findUserByUsername(username);
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    public int updateUser(User user) {
        Map map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        if (user.getId() == id){
            int result = userMapper.updateUser(user);
            if (result == 0){
                throw new RuntimeException(MessageConstant.UPDATE_FAIL);
            }
            return result;
        }else {
            throw new RuntimeException(MessageConstant.LOGIN_FAIL);
        }
    }

    @Override
    public void register(User user) {
        userMapper.insert(user);
    }
}
